/* eslint-disable react-hooks/exhaustive-deps */
'use client'

import Link from 'next/link'
import { AnimatePresence, motion } from "framer-motion"
import React, { useEffect, useRef, useState } from 'react'
import {
    FileImage,
    Mic,
    Paperclip,
    PlusCircle,
    SendHorizonal,
    ThumbsUp
} from 'lucide-react'

import {
    Popover,
    PopoverContent,
    PopoverTrigger
} from '@/components/ui/popover'
import { Textarea } from '@/components/ui/textarea'
import { buttonVariants } from '@/components/ui/button'
import EmojiPicker from '@/components/ai/chat/emoji-picker'

import { cn } from '@/lib/utils'
import { Speaker } from '@/lib/speech/speaker'
import { useAvatar } from '@/hooks/use-avatar'
import { useSpeech } from '@/hooks/use-speech'
import { useChatContextSelector } from '@/context/chat-context'

export const BottombarIcons = [{ icon: FileImage }, { icon: Paperclip }]
const ChatInput = () => {
    const setSpeaker = useSpeech(state => state.setSpeaker)

    const [input, setInput] = useState<string>('')
    const inputRef = useRef<HTMLTextAreaElement>(null)

    const avatar = useAvatar(state => state.avatar)
    const sendMessage = useChatContextSelector(state => state.sendMessage)

    useEffect(() => setSpeaker(new Speaker()), [setSpeaker])

    const handleThumbsUp = () => {
        sendMessage('👍')
        setInput('')
    }

    const handleSend = () => {
        const content = input.trim()
        if (content) {
            sendMessage(content)
            setInput('')
        }
    }

    const handleKeyPress = (event: React.KeyboardEvent<HTMLTextAreaElement>) => {
        if (event.key === 'Enter' && !event.shiftKey) {
            event.preventDefault()
            handleSend()
        }
        if (event.key === 'Enter' && event.shiftKey) {
            event.preventDefault()
            setInput(prev => prev + '\n')
        }
    }

    return (
        <div className='p-2 flex justify-between w-full items-center gap-2'>
            <div className='flex'>
                <Popover>
                    <PopoverTrigger asChild>
                        <Link
                            href='#'
                            className={cn(
                                buttonVariants({ variant: 'ghost', size: 'icon' }),
                                'h-9 w-9',
                            )}
                        ><PlusCircle size={20} className='text-muted-foreground' /></Link>
                    </PopoverTrigger>
                    <PopoverContent side='top' className='w-full p-2'>
                        <Link
                            href='#'
                            className={cn(
                                buttonVariants({ variant: 'ghost', size: 'icon' }),
                                "h-9 w-9",
                            )}
                        ><Mic size={20} className='text-muted-foreground' /></Link>
                        {BottombarIcons.map((icon, index) => (
                            <Link
                                key={index}
                                href='#'
                                className={cn(
                                    buttonVariants({ variant: 'ghost', size: 'icon' }),
                                    'h-9 w-9',
                                    !input.trim() && 'md:hidden'
                                )}
                            ><icon.icon size={20} className='text-muted-foreground' /></Link>
                        ))}
                    </PopoverContent>
                </Popover>
                {!input.trim() && (
                    <div className='flex'>
                        {BottombarIcons.map((icon, index) => (
                            <Link
                                key={index}
                                href='#'
                                className={cn(
                                    buttonVariants({ variant: 'ghost', size: 'icon' }),
                                    "h-9 w-9",
                                    'max-md:hidden'
                                )}
                            ><icon.icon size={20} className='text-muted-foreground' /></Link>
                        ))}
                    </div>
                )}
            </div>

            <AnimatePresence initial={false}>
                <motion.div
                    key='input'
                    className='w-full relative'
                    layout
                    initial={{ opacity: 0, scale: 1 }}
                    animate={{ opacity: 1, scale: 1 }}
                    exit={{ opacity: 0, scale: 1 }}
                    transition={{
                        opacity: { duration: 0.05 },
                        layout: { type: 'spring', bounce: 0.15 }
                    }}
                >
                    <Textarea
                        autoComplete='off'
                        value={input}
                        ref={inputRef}
                        onKeyDown={handleKeyPress}
                        onChange={event => setInput(event.target.value)}
                        name='message'
                        placeholder='Aa'
                        className='min-h-0 shadow-sm focus-visible:ring-1 focus-visible:ring-offset-0 w-full border rounded-full flex items-center h-9 resize-none overflow-hidden bg-background'
                    />
                    <div className='absolute right-2 bottom-0.5'>
                        <EmojiPicker onChange={value => {
                            setInput(input + value)
                            inputRef.current?.focus()
                        }} />
                    </div>
                </motion.div>
                {input.trim() ? (
                    <Link
                        href='#'
                        className={cn(
                            buttonVariants({ variant: "ghost", size: "icon" }),
                            "h-9 w-9",
                        )}
                        onClick={handleSend}
                    ><SendHorizonal size={20} className='text-muted-foreground' /></Link>
                ) : (
                    <Link
                        href='#'
                        className={cn(
                            buttonVariants({ variant: "ghost", size: "icon" }),
                            "h-9 w-9",
                        )}
                        onClick={handleThumbsUp}
                    ><ThumbsUp size={20} className='text-muted-foreground' /></Link>
                )}
            </AnimatePresence>
        </div>
    )
}

export default ChatInput